﻿// ....................................................................................................................
//	Author: Copyright (C) 2012 Ing. Marek Hubal
//	Email: hubal@acasoftware.org
// ....................................................................................................................

using System;

namespace core
{
    /// <summary>Trieda IJoinFilesDataStruct</summary>
    public class IJoinFilesDataStruct
    {
        public System.Collections.Generic.List<string> SourceFiles; // Zoznam zdrojovych suborov
        public string DestinationFolder; // Cielova cesta
        public string DestinationFileName; // Nazov cieloveho suboru
        public bool CheckCRC; // Priznak testovania CRC

        /// <summary>Konstruktor</summary>
        public IJoinFilesDataStruct()
        {
            SourceFiles = new System.Collections.Generic.List<string>();
            DestinationFileName = "";
            DestinationFolder = "";
            CheckCRC = false;
        }

        /// <summary>Skopirovanie obsahu objektu</summary>
        /// <param name="pValue">objekt na skopirovanie</param>
        public void Assign(IJoinFilesDataStruct pValue)
        {
            DestinationFileName = pValue.DestinationFileName;
            DestinationFolder = pValue.DestinationFolder;
            CheckCRC = pValue.CheckCRC;
            SourceFiles.Clear(); SourceFiles.AddRange(pValue.SourceFiles);
        }
        /// <summary>Editacia obsahu pomocou formulara</summary>
        /// <returns>true / false</returns>
        public bool EditWithForm()
        {
            using (IFileExplorerForm_JoinFiles F = new IFileExplorerForm_JoinFiles())
            {
                F.Value.Assign(this); // Skopirujem obsah
                bool B = F.ShowDialog() == System.Windows.Forms.DialogResult.OK; // Zobrazim okno
                if (B) Assign(F.Value); // Skopirujem vysledok
                return B;
            }
        }

        /// <summary>Ziskanie kandidata na nazov vysledneho suboru</summary>
        /// <returns>nazov</returns>
        public string GetDestinationCandidateFileName()
        {
            if (SourceFiles.Count == 0) return ""; // Prazdny zoznam?
            
            System.Collections.Generic.Dictionary<string, int> FHashTable = new System.Collections.Generic.Dictionary<string, int>(); // Budem pocitat vyskyty
            foreach (string FN in SourceFiles)
            {
                string FN1 = IFileSystem.ExtractNameOnly(IFileSystem.ExtractName(FN)).ToLower();
                if (FHashTable.ContainsKey(FN1)) FHashTable[FN1]++;
                else FHashTable.Add(FN1, 1);
            }

            int MaxC = 0; string MaxFN = "";
            foreach (System.Collections.Generic.KeyValuePair<string, int> V in FHashTable) // Hladam maximum
            {
                if (V.Value > MaxC)
                {
                    MaxC = V.Value;
                    MaxFN = V.Key;
                }
            }
            return MaxFN; // Vratim nazov s max. vyskytom
        }
        /// <summary>Pokus o ziskanie hodnoty CRC32 zo zadaneho obsahu</summary>
        /// <param name="pData">obsah</param>
        /// <returns>najdena CRC32 hodnota alebo </returns>
        public string TryExtractCRC32Value(string pData)
        {
            try
            {
                string[] Lines = pData.ToUpper().Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string L in Lines)
                {
                    string L1 = L.Trim(); // Vycistim
                    if (!L1.StartsWith("CRC32")) continue; // Nezacina sa crc32?

                    int I = L1.IndexOf('=');
                    if (I == -1) continue; // Nema znak '='
                    return L1.Substring(I + 1).Trim(); // Vratim najdenu CRC32 hodnotu
                }
                return ""; // Nic som nenasiel
            }
            catch
            {
                return ""; // Chyba
            }
        }
    }

    /// <summary>Trieda IFileExplorerForm_JoinFiles</summary>
    public class IFileExplorerForm_JoinFiles : IForm
    {
        public IJoinFilesDataStruct Value;

        protected IGroupBox FGrp; // Controls
        protected IButton FBtn_OK;
        protected IButton FBtn_Cancel;

        protected IGroupBox FGrp1;
        protected ILabel FLabel1;
        protected IListBox FList;
        protected IButton FUpBtn, FDownBtn;
        protected ILabel FLabel2;
        protected ITextBox FText_DestPath;
        protected ILabel FLabel3;
        protected ITextBox FText_DestName;
        protected ICheckBox FCheck_UseCRC;

        /// <summary>Konstruktor</summary>
        public IFileExplorerForm_JoinFiles()
        {
            Value = new IJoinFilesDataStruct(); // Inicializacia
        }

        /// <summary>Metoda: OnCreateForm</summary>
        /// <returns>true / false</returns>
        protected override bool OnCreateForm()
        {
            if (!base.OnCreateForm()) return false; // Volam predchodcu

            // Inicializacia
            MinimizeBox = false; MaximizeBox = false; FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; ShowIcon = true; ShowInTaskbar = false; StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;

            SetBounds(0, 0, 400, 540); System.Drawing.Size CS = ClientSize;
            Text = lang.FORM_EDIT_JOIN_FILES_TEXT_1;

            // Vytvorim groupbox
            FGrp = new IGroupBox(); IControl.PlaceControl_Inside(FGrp, this, 10, 10, 10, 50);
            System.Drawing.Size CS1 = FGrp.ClientSize;

            // Vytvorim tlacidla
            FBtn_Cancel = new IButton(lang.FORM_EDIT_JOIN_FILES_TEXT_3); IControl.PlaceControl_Outside_TopRight_RightBottom(FBtn_Cancel, FGrp, 0, 10); FBtn_Cancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            FBtn_OK = new IButton(lang.FORM_EDIT_JOIN_FILES_TEXT_2, Event_BtnOKClick); IControl.PlaceControl_Outside_TopRight_LeftTop(FBtn_OK, FBtn_Cancel, 0, 10);

            FGrp1 = new IGroupBox(); IControl.PlaceControl_Inside_LeftTop_LeftTop(FGrp1, FGrp, 10, 10, FGrp.ClientSize.Width - 20, 300);
            FLabel1 = new ILabel(lang.FORM_EDIT_JOIN_FILES_TEXT_4);
            FList = new IListBox();
            FUpBtn = new IButton(lang.FORM_EDIT_JOIN_FILES_TEXT_5_1); FDownBtn = new IButton(lang.FORM_EDIT_JOIN_FILES_TEXT_5_2);

            FGrp1.Controls.AddRange(new System.Windows.Forms.Control[] { FLabel1, FList, FUpBtn, FDownBtn });
            IControl.PlaceControl_Inside_LeftTop_LeftTop(FLabel1, FGrp1, 10, 18);
            IControl.PlaceControl_Outside_LeftTop_LeftBottom(FList, FLabel1, 0, 6, FGrp1.ClientSize.Width - 20, FGrp1.ClientSize.Height - 80);
            IControl.PlaceControl_Outside_TopRight_RightBottom(FDownBtn, FList, 0, 4);
            IControl.PlaceControl_Outside_TopRight_LeftTop(FUpBtn, FDownBtn, 0, 10);

            FLabel2 = new ILabel(lang.FORM_EDIT_JOIN_FILES_TEXT_6);
            FText_DestPath = new ITextBox(); FText_DestPath.ReadOnly = true;
            FLabel3 = new ILabel(lang.FORM_EDIT_JOIN_FILES_TEXT_7);
            FText_DestName = new ITextBox();
            FCheck_UseCRC = new ICheckBox(lang.FORM_EDIT_JOIN_FILES_TEXT_8);

            FGrp.Controls.AddRange(new System.Windows.Forms.Control[] { FGrp1, FLabel2, FText_DestPath, FLabel3, FText_DestName, FCheck_UseCRC });

            IControl.PlaceControl_Outside_LeftTop_LeftBottom(FLabel2, FGrp1, 0, 10);
            IControl.PlaceControl_Outside_LeftTop_LeftBottom(FText_DestPath, FLabel2, 0, 6, CS1.Width - 20);
            IControl.PlaceControl_Outside_LeftTop_LeftBottom(FLabel3, FText_DestPath, 0, 10);
            IControl.PlaceControl_Outside_LeftTop_LeftBottom(FText_DestName, FLabel3, 0, 6, CS1.Width - 20);
            IControl.PlaceControl_Outside_LeftTop_LeftBottom(FCheck_UseCRC, FText_DestName, 0, 10);

            Controls.AddRange(new System.Windows.Forms.Control[] { FGrp, FBtn_OK, FBtn_Cancel }); // Zaradim do controls

            AcceptButton = FBtn_OK; CancelButton = FBtn_Cancel; FBtn_OK.Focus();

            FillForm(Value); // Vyplnim zaciatocnou hodnotou

            FUpBtn.Click += (s, e) =>
            {
                int I = FList.SelectedIndex; // Presun aktivneho zaznamu hore
                if (I > 0)
                {
                    string S = ICore.ToStr(FList.Items[I - 1]); FList.Items[I - 1] = FList.Items[I]; FList.Items[I] = S; // Vymenim v listboxe
                    S = Value.SourceFiles[I - 1]; Value.SourceFiles[I - 1] = Value.SourceFiles[I]; Value.SourceFiles[I] = S; // Vymenim v zozname
                    FList.SelectedIndex = I - 1;
                }
            };

            FDownBtn.Click += (s, e) =>
            {
                int I = FList.SelectedIndex; // Presun aktivneho zaznamu dole
                if ((I != -1) && (I < FList.Items.Count - 1))
                {
                    string S = ICore.ToStr(FList.Items[I + 1]); FList.Items[I + 1] = FList.Items[I]; FList.Items[I] = S; FList.SelectedIndex = I + 1; // Vymenim v listboxe
                    S = Value.SourceFiles[I + 1]; Value.SourceFiles[I + 1] = Value.SourceFiles[I]; Value.SourceFiles[I] = S; // Vymenim v zozname
                }
            };

            FList.Focus(); FList.SelectedIndex = 0;
            return true; // Vsetko OK
        }

        /// <summary>Vyplnenie formulara</summary>
        /// <param name="pValue">vyplnenie formulara</param>
        protected void FillForm(IJoinFilesDataStruct pValue)
        {
            FText_DestName.Text = pValue.DestinationFileName;
            FText_DestPath.Text = pValue.DestinationFolder;
            FCheck_UseCRC.Checked = pValue.CheckCRC;
            
            FList.BeginUpdate();
            foreach (string L in pValue.SourceFiles) FList.Items.Add(IFileSystem.ExtractName(L));
            FList.EndUpdate();
        }
        /// <summary>Otestovanie validity dat formulara</summary>
        /// <returns>true / false</returns>
        protected bool CheckForm()
        {
            if (string.IsNullOrWhiteSpace(FText_DestName.Text)) // Test nazvu suboru
            {
                IApp.ShowError(lang.FORM_EDIT_JOIN_FILES_TEXT_9);
                FText_DestName.Focus();
                return false;
            }
            return true; // Vsetko OK
        }
        /// <summary>Nacitanie obsahu formulara</summary>
        /// <param name="Result">vysledok</param>
        protected void ReadForm(IJoinFilesDataStruct Result)
        {
            Result.DestinationFileName = FText_DestName.Text.Trim();
            Result.CheckCRC = FCheck_UseCRC.Checked;
        }

        /// <summary>Event: Click pre tlacidlo OK</summary>
        /// <param name="pSender">zdroj</param>
        /// <param name="e">parameter</param>
        protected void Event_BtnOKClick(object pSender, EventArgs e)
        {
            if (!CheckForm()) return; // Kontrola validity

            ReadForm(Value); // Nacitam data
            DialogResult = System.Windows.Forms.DialogResult.OK;
        }
    }
}
